#!/usr/bin/evn python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   文件名称 :     update
   文件功能描述 :   功能描述
   创建人 :       小钟同学
   创建时间 :          2021/7/12
-------------------------------------------------
   修改描述-2021/7/12:         
-------------------------------------------------
"""
from dataclasses import dataclass
from afast_core.core_libs.zyxorm.models.base import Base
from afast_core.core_libs.zyxorm.exceptions import ClientConfigBadException
import collections


@dataclass
class Update(Base):
    pass

    # 要刷选的字段信息，默认是全部字段都刷新

    # 自减
    def decrement(self, key, amount=1):
        if isinstance(amount, int) and amount > 0:
            data = collections.defaultdict(dict)
            data[key] = '{}-{}'.format(str(key), str(amount))
            self.__sql__ = self._compile_increment(data)
            return self

    # 自增
    def increment(self, key, amount=1):
        if isinstance(amount, int) and amount > 0:
            data = collections.defaultdict(dict)
            data[key] = '{}+{}'.format(str(key), str(amount))
            self.__sql__ = self._compile_increment(data)
            return self

    # 组合
    def _compile_update(self, data):
        if not self.select_table:
            raise ClientConfigBadException(errmsg='请设置需要查询查询的表')

        return "update {} set {}{}{}".format(self.select_table, ','.join(self._compile_dict(data)),
                                             self._compile_where(), self._compile_returning())

    def _compile_increment(self, data):
        if not self.select_table:
            raise ClientConfigBadException(errmsg='请设置需要查询查询的表')
        subsql = ','.join(['{}={}'.format(str(index), value) for index, value in data.items()])
        return "update {} set {}{}{}".format(self.select_table, subsql, self._compile_where(),
                                             self._compile_returning())

    # 查询
    def update(self, data):
        if data and isinstance(data, dict):
            data = {key: value for key, value in data.items()}
            self.__sql__ = self._compile_update(data)
            return self
